﻿using DLL.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

namespace DLL.Repository
{
    public class ShiftRepositiry : IShiftRepositiry
    {
        private readonly AppDbContext _db;

        public ShiftRepositiry(AppDbContext db)
        {
            _db = db;
        }


        public async Task Create(WorkShift item)
        {
            var entry = _db.Entry(item);
            if (entry.State == EntityState.Detached)
                _db.WorkShifts.Add(item);
            await _db.SaveChangesAsync();
        }

        public async Task Delete(WorkShift item)
        {
            var result = await GetById(item.Id);
            if (result != null)
            {
                _db.WorkShifts.Remove(item);
                await _db.SaveChangesAsync();
            }
        }

        public async Task<IEnumerable<WorkShift>> GetAll()
        {
            return await _db.WorkShifts
               .ToListAsync();
        }

        public async Task<WorkShift> GetById(Guid id)
        {
            return await _db.WorkShifts
                .FirstOrDefaultAsync(i => i.Id == id);
        }

        public async Task<IEnumerable<WorkShift>> GetNotClosedByEmployee(Guid employee)
        {
            return await _db.WorkShifts
                .Where(shift => !shift.Done & shift.EmployeeId==employee)
                .ToListAsync();
        }

        public async Task Update(WorkShift item)
        {
            var result = await GetById(item.Id);
            if (result != null)
            {
                _db.WorkShifts.Update(item);
                await _db.SaveChangesAsync();
            }
        }
    }
}
